﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;

namespace FilteredTaskSite.VisualWebPart1
{
    public partial class VisualWebPart1UserControl : UserControl
    {
        DateTimeControl filterDate;
        ListViewByQuery MyCustomView;
        SPQuery listQuery; 
        
        protected void Page_Load(object sender, EventArgs e)
        {
            filterDate = new DateTimeControl();
            filterDate.DateOnly = true;
            filterDate.AutoPostBack = true;
            filterDate.DateChanged += new EventHandler (filterDate_DateChanged);
            SPWeb thisWeb = SPContext.Current.Web;
            MyCustomView = new ListViewByQuery();
            MyCustomView.List = thisWeb.Lists["List Items"];
            listQuery = new SPQuery(MyCustomView.List.DefaultView);
            listQuery.ViewFields =
                "<FieldRef Name='Category' /><FieldRef Name='Assignment' /><FieldRef Name='DueBy' />";
            MyCustomView.Query = listQuery;
            LiteralControl filterMessage = new LiteralControl ("Assignments are due by:");
            this.Controls.Add(filterMessage);
            this.Controls.Add(new LiteralControl("<br/>"));
            this.Controls.Add(filterDate);
            this.Controls.Add(new LiteralControl("<br/>"));
            this.Controls.Add(MyCustomView);
        }
        void filterDate_DateChanged(object sender, EventArgs e)
        {
            string camlQuery = "<Where><Leq><FieldRef Name='DueBy' />"
            + "Value Type='DateTime'>"
            + SPUtility.CreateISO8601DateTimeFromSystemDateTime(filterDate.SelectedDate)
            + "<Value /></Leq></Where>";
            listQuery.Query=camlQuery;
            MyCustomView.Query=listQuery;

        }
    }
}
